import { defineStore } from 'pinia'
import { computed,ref } from 'vue'
import { useUserStore } from './userStore'
import { findNewCartListAPI,insertCartAPI,delCartAPI,updateCartItem } from '@/apis/cart'

export const useCartStore = defineStore(
    'cart',
    () => {
        const cartList = ref([])

        const userStore = useUserStore()
        const isLogin = computed(() => userStore.userInfo.token)

        //获取登录后最新的购物车列表
        const updateLoginCartList = async () => {
            const { result } = await findNewCartListAPI()
            cartList.value = result
        }



        
        const addCart = async (goods) => {
            if(isLogin.value) {
                await insertCartAPI(goods)
                await updateLoginCartList()
            }else {
            //判断商品是否在购物车
            const findItem = cartList.value.find(item => goods.skuId === item.skuId)
            if(findItem) {
                findItem.count += goods.count
            }else {
                cartList.value.push(goods)
                }
            }
        }

        const delCart = async (skuId) => {
            if(isLogin.value){
                await delCartAPI([skuId])
                await updateLoginCartList()
            }else {
            const index = cartList.value.findIndex(item => skuId === item.skuId)
            cartList.value.splice(index,1)
            }
        }


        //全选功能
        const checkAll = (selected) => {
            cartList.value.forEach(item => item.selected = selected)
        }

        //清除购物车
        const clearCart = () => {
            cartList.value = []
        }

        //修改购物项
        const updateCart = async (goods) => {
            const { skuId,count,selected }  = goods
            if(isLogin.value){
                await updateCartItem(skuId,{count,selected})
            }
        }

        //计算属性
        //总的数量
        const allCount = computed(() => cartList.value.reduce((pre,current) => pre + current.count,0))
        //总的价格
        const allPrice = computed(() => cartList.value.reduce((pre,current) => pre + current.price * current.count,0))

        //是否全选的计算属性
        const isAll = computed(() => cartList.value.every(item => item.selected))

        //已选择的数量
        const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((pre,current) => pre + current.count,0))

        //已选择商品价格和
        const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((pre,current) => pre + current.count * current.price,0))

        return {
            cartList,
            addCart,
            delCart,
            checkAll,
            updateLoginCartList,
            clearCart,
            updateCart,
            allCount,
            allPrice,
            isAll,
            selectedCount,
            selectedPrice
        }
    },
    {
        persist:true
    }
)